/* 
 * File:   sem.cpp
 * Author: zhouxich
 * Description: 用信号量跟互斥锁实现互斥访问任务队列的函数
 */
#include "server.h"

void
task_init(task_handler* th, int n){
	/*初始化*/
	pthread_mutex_init(&th->mutex, NULL);	
	sem_init(&th->not_full, 0, n);
	sem_init(&th->not_empty, 0, 0);
}

void
task_insert(task_handler* th, task ts){

	/*等待队列不满*/
	sem_wait(&th->not_full);
	/*申请进入临界区*/
	pthread_mutex_lock(&th->mutex);
	/*把新任务加入任务队列*/
	th->task_queue.push(ts);
	/*释放互斥锁*/
	pthread_mutex_unlock(&th->mutex);
	/*唤醒消费者*/
	sem_post(&th->not_empty);
}

task
task_get(task_handler* th){

	task temp;
	/*等待任务*/
	sem_wait(&th->not_empty);
	/*申请进入临界区*/
	pthread_mutex_lock(&th->mutex);
	/*取出任务*/
	temp = th->task_queue.front();
	th->task_queue.pop();
	/*释放互斥锁*/
	pthread_mutex_unlock(&th->mutex);
	/*唤醒生产者*/
	sem_post(&th->not_full);
	return temp;
}
